package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.webapi.BDFaceToken;
import com.ocom.redis.util.RedisUtil;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.utils.GsonUtils;
import com.ocom.webapi.utils.HttpUtil;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/7/7
 **/
@RestController
public class OauthController {

	@PreAuthorize("@pms.hasPermission('order_get')" )
	@GetMapping("auth2")
	public String gt(){
		return  "yuu";
	}


	@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
	@GetMapping("auth3")
	public String gt3(){
		return  "yuu";
	}

	@Resource
	RedisUtil redisUtil;

	//  http://47.113.206.142:5500/webapi/oauthLogout  退出测试
    //  http://47.113.206.142:5500/auth/login

	/**
	 * username: 520111
	 * password: 123456
	 * sms_code: 0271
	 * grant_type: code_auth
	 * client_id: client_1
	 * client_secret: 123456
	 * @return
	 */



	@GetMapping("/oauthLogout")
	public String logout(){
		YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
		redisUtil.set("blacklist:logout:"+yoCiUser.getForm(),1,86400l);
		return  "success";
	}


	@PostMapping("/checkUserPhoto")
	public Object checkUserPhoto(@RequestPart("file") MultipartFile file){
		String base646 = "";
		try {
			byte[] bytes = file.getBytes(); // 获取文件内容的字节数组
			base646 =  Base64Utils.encodeToString(bytes); // 将字节数组编码成 base64 字符串
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		String ytr = faceDetect(base646);
		BDFaceToken bdFaceToken = JSON.parseObject(ytr, BDFaceToken.class);

		if(bdFaceToken.getErrorCode()!=0){
			return ResultUtil.info(bdFaceToken.getErrorCode(),bdFaceToken.getErrorMsg());
		}


		List<String>  stringList =new ArrayList<>();
		Float faceProbability = Float.parseFloat( bdFaceToken.getResult().getFaceList().get(0).getFaceProbability().toString());
		if(faceProbability!=1f){
			stringList.add("人脸置信度不为1,当前:"+faceProbability);
		}
		String gsType = (String) bdFaceToken.getResult().getFaceList().get(0).getGlasses().get("type");
		if(!gsType.equals("none")){
			stringList.add("检测戴眼镜不通过，当前:"+gsType);
		}

		Float rightEye =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getEyeStatus().get("right_eye").toString()) ;
		if(rightEye<0.9f){
			stringList.add("右眼闭合度检测不通过，当前:"+rightEye);
		}

		Float leftEye =Float.parseFloat( bdFaceToken.getResult().getFaceList().get(0).getEyeStatus().get("left_eye").toString()) ;
		if(leftEye<0.9f){
			stringList.add("左眼闭合度检测不通过，当前:"+leftEye);
		}
		String faceType =(String) bdFaceToken.getResult().getFaceList().get(0).getFaceType().get("type");
		if(!faceType.equals("human")){
			stringList.add("人脸类型不通过，当前:"+faceType);
		}
		Float probability =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getFaceType().get("probability").toString()) ;
		if(probability<0.7f){
			stringList.add("人脸类型判断正确的置信度检测不通过，当前:"+probability);
		}
		Integer mask =(Integer)bdFaceToken.getResult().getFaceList().get(0).getMask().get("type");
		if(mask==1){
			stringList.add("口罩检测，当前检测到口罩");
		}
	//	objectMap.put("口罩置信度，范围0~1",bdFaceToken.getResult().getFaceList().get(0).getMask().get("probability"));
		Float pleftEye =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("left_eye").toString()) ;
		if(pleftEye>0.2f){
			stringList.add("左眼遮挡比例检测不通过，当前:"+pleftEye);
		}
		Float prightEye =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("right_eye").toString()) ;
		if(prightEye>0.2f){
			stringList.add("右眼遮挡比例检测不通过，当前:"+prightEye);
		}

		Float pnose =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("nose").toString()) ;
		if(pnose>0.2f){
			stringList.add("鼻子遮挡比例检测不通过，当前:"+pnose);
		}
		Float pmouth =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("mouth").toString()) ;
		if(pmouth>0.2f){
			stringList.add("嘴巴遮挡比例检测不通过，当前:"+pmouth);
		}
		Float pleftCheek =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("left_cheek").toString()) ;
		if(pleftCheek>0.2f){
			stringList.add("左脸颊遮挡比例检测不通过，当前:"+pleftCheek);
		}
		Float prightCheek =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("right_cheek").toString()) ;
		if(prightCheek>0.2f){
			stringList.add("右脸颊遮挡比例检测不通过，当前:"+prightCheek);
		}
		Float pchinContour =Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("chin_contour").toString()) ;
		if(pchinContour>0.2f){
			stringList.add("下巴遮挡比例检测不通过，当前:"+pchinContour);
		}
		Float blur = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getBlur().toString()) ;
		if(blur>0.2f){
			stringList.add("人脸模糊程度检测不通过，当前:"+blur);
		}
		Float completeness =Float.parseFloat( bdFaceToken.getResult().getFaceList().get(0).getQuality().getCompleteness().toString()) ;
		if(completeness!=1f){
			stringList.add("人脸完整度检测不通过，当前:"+completeness);
		}

		Integer illumination = bdFaceToken.getResult().getFaceList().get(0).getQuality().getIllumination();
		if(illumination<140){
			stringList.add("光照程度检测不通过，当前:"+illumination);
		}

		return stringList;

	}

	/**
	 * 获取权限token
	 *
	 * @return 返回示例：
	 * {
	 * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
	 * "expires_in": 2592000
	 * }
	 */
	public static String getAuth() {
		// 官网获取的 API Key 更新为你注册的
		String clientId = "gyDN7d1nnqGgrGf1ezonroCH";
		// 官网获取的 Secret Key 更新为你注册的
		String clientSecret = "sjO8vOE6LEAkaVBRiednpzgL9TT0Ofca";
		return getAuth(clientId, clientSecret);
	}

	/**
	 * 获取API访问token
	 * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
	 *
	 * @param ak - 百度云官网获取的 API Key
	 * @param sk - 百度云官网获取的 Securet Key
	 * @return assess_token 示例：
	 * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
	 */
	public static String getAuth(String ak, String sk) {
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + ak
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + sk;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			/**
			 * 返回结果示例
			 */
			System.err.println("result:" + result);
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			System.err.printf("获取token失败！");
			e.printStackTrace(System.err);
		}
		return null;
	}


	/**
	 * 重要提示代码中所需工具类
	 * FileUtil,Base64Util,HttpUtil,GsonUtils请从
	 * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
	 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
	 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
	 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
	 * 下载
	 */
	public static String faceDetect(String base64) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("image", base64);
			map.put("image_type", "BASE64");
			map.put("face_field", "age,expression,face_shape,gender,glasses,quality,eye_status,emotion,face_type,mask,spoofing");


			String param = GsonUtils.toJson(map);

			// 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			String accessToken = getAuth();

			String result = HttpUtil.post(url, accessToken, "application/json", param);
			System.out.println(result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	public static String faceDetect1() {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/face/v1/feature";
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("image", "http://file.ocomtraffic.com/daily/2024/01/10/78c0dc27-d88d-4db5-ae01-324b65312e38.jpg");
			map.put("image_type", "URL");
			map.put("version", "4300");


			String param = GsonUtils.toJson(map);

			// 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			String accessToken = getAuth();

			String result = HttpUtil.post(url, accessToken, "application/json", param);
			System.out.println(result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args){
		System.out.println(faceDetect1());;
	}

//
}
